﻿using Dapper;
using Dapper_Core.Basic;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Dapper_Core.DAL.Impl
{
    public static class BaseRepositoryExt
    {
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程的名称</param>
        /// <param name="parameters">所需参数</param>
        /// <returns></returns>
        public static IEnumerable<T2> ExecuteProcQuery<T, T2>(this BaseRepository<T> repository, string procName, object parameters) 
            where T : BaseModel, new()
        {
            try
            {
                repository.InitialState();
                return repository.connection.Query<T2>(procName, parameters, repository.transaction, commandType: CommandType.StoredProcedure);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (repository.transaction == null && repository.connection != null && repository.connection.State == ConnectionState.Open)
                    repository.connection.Close();
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程的名称</param>
        /// <param name="parameters">所需参数</param>
        /// <returns></returns>
        public static T2 ExecuteProcModel<T, T2>(this BaseRepository<T> repository, string procName, object parameters)
            where T : BaseModel, new()
        {
            try
            {
                return repository.ExecuteProcQuery<T,T2>(procName, parameters).FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (repository.transaction == null && repository.connection != null && repository.connection.State == ConnectionState.Open)
                    repository.connection.Close();
            }
        }
    }
}
